package com.starinside.wp.utils;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Created by xsy on 17-7-12.
 */
public class JarFileUtils {

    public static void copyDirFromJarByNIO(URL url, String dir, String destDir) throws IOException {

        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
        JarFile jarFile = jarURLConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();

        Path userDir = Paths.get(destDir);
        while (entries.hasMoreElements()){
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            Path path = Paths.get(userDir.toString(), name);
            if (!name.startsWith(dir)) continue;
            if (name.endsWith("/")){
                if (Files.exists(path)) continue;
                Files.createDirectory(path);
            } else {
                Files.copy(jarFile.getInputStream(jarEntry),path, StandardCopyOption.REPLACE_EXISTING);
            }
        }
    }

    public static void copyDirFromJar(URL url, String dir, String destDir) throws IOException {

        File destFile = new File(destDir);
        if (!destFile.exists()) destFile.mkdir();
        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
        JarFile jarFile = jarURLConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        System.out.println("output:"+destDir);
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.startsWith(dir)) {
                String dest = name.substring(0, name.lastIndexOf("/"));
                if (name.endsWith("/")) {
                    new File(destDir, dest).mkdir();
                } else {
                    File f = new File(destDir, name);
                    f.createNewFile();
                    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry(name)), new FileOutputStream(f));
                }
            }
        }
    }
}
